<?php

namespace app\api\controller\web;

use app\admin\model\apply\Confg;
use app\admin\model\apply\Video;
use app\admin\model\memberpoint\Integral;
use app\admin\model\nursery\Companyattestation;
use app\admin\model\nursery\NurserySell;
use app\admin\model\nursery\NurseryWantbuyOffer;
use app\admin\model\nursery\Specs;
use app\admin\model\nursery\Wantbuy;
use app\admin\model\Type;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\model\Attachment;
use app\common\model\ScoreLog;
use app\common\model\User;
use fast\Tree;
use think\Cache;
use think\Model;
use think\Validate;


class Want extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 求购列表
     */
    public function wantBuyList()
    {
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $startTime = $this->request->param('startTime');
        $entTime = $this->request->param('endTime');
        $province_id = $this->request->param('province_id');
        $city_id = $this->request->param('city_id');
        $county_id = $this->request->param('county_id');

        $where = [
            'w.is_del'=> 0,
            'w.status'=> "1",
            'u.status'=>"normal"
        ];

        if($province_id){
            $where['w.province_id'] = $province_id;
        }
        if($city_id){
            $where['w.city_id'] = $city_id;
        }
        if($county_id){
            $where['w.county_id'] = $county_id;
        }
        if($startTime && $entTime){
            $where['w.create_time'] = ['between', [$startTime, $entTime]];;
        }
        $model =  (new Wantbuy())->alias('w')
            ->field('w.id,w.name,w.imgs,w.specs_config,w.address,w.introduction,w.create_time,w.num,u.nickname,u.level,w.user_id')
            ->join('user u','w.user_id = u.id','left')
            ->where($where)
            ->order('u.level desc,w.create_time desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total = $model->total();
        $list =  $model->items();
        if($list){
            $specsList = (new Specs())->select();
            foreach ($list as &$v){
                $v['img'] = '';
                $v['imgs'] =ImageUtil::handleMore($v['imgs']);
                if(count($v['imgs']) > 0){
                    $v['img'] = $v['imgs'][0];
                }
                $v['specs_config'] = Index::specsConfig($v['specs_config'],$specsList);
            }
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("请求成功", $result);
    }


    /**
     * 求购上传
     */
    public function myBuySub()
    {
        $validate = new \think\Validate([
            ['name', 'require', '苗木名称不能为空'],
            ['introduction', 'require', '产品简介不能为空'],
            ['lvl', 'require', '苗木等级不能为空'],
            ['phone', 'require', '电话号码不能为空'],
            ['imgs', 'require', '图片不能为空'],
            ['num', 'require', '数量不能为空'],
            ['effective_time', 'require', '有效时间不能为空'],
            ['address', 'require', '地址不能为空'],
            ['province_id', 'require', '省份不能为空'],
            ['city_id', 'require', '市不能为空'],
            ['county_id', 'require', '区县不能为空'],
        ]);

        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $user = $this->auth->getUser();
        $name = $this->request->param('name');
        $specs_config = $this->request->param('specs_config');
        $introduction = $this->request->param('introduction');
        $lvl = $this->request->param('lvl');
        $phone = $this->request->param('phone');
        $num = $this->request->param('num');
        $effective_time = $this->request->param('effective_time');
        $company_name = $this->request->param('company_name');
        $address = $this->request->param('address');
        $imgs = $this->request->param('imgs');
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');
        $province_id = $this->request->param('province_id');
        $city_id = $this->request->param('city_id');
        $county_id = $this->request->param('county_id');

        if(!preg_match("/^[0-9][0-9]*$/",$num)){
            $this->error("数量请输入正整数");
        }

        $imgArr = explode(',',$imgs);
        if(count($imgArr)>6){
            $this->error("图片最多上传6张");
        }

        $data=[
            'user_id'=>$user['id'],
            'name'=>$name, //苗木名称
            'imgs'=>$imgs,
            'specs_config'=>$specs_config, //规格配置
            'introduction'=>$introduction, //产品简介
            'lvl'=>$lvl,
            'phone'=>$phone,
            'num'=>$num,
            'effective_time'=>$effective_time,
            'company_name'=>$company_name,
            'address'=>$address, //地址
            'province_id'=>$province_id,
            'city_id'=>$city_id,
            'county_id'=>$county_id,
            'area'=>$this->request->param('area',''),
            'lng'=>$lng,
            'lat'=>$lat,
        ];

        $id = $this->request->param('id');
        if($id){
            $info = Wantbuy::update($data,['id'=>$id]);
            if(!$info){
                $this->success("没有更新");
            }
        }else{
            $data['create_time'] = date('Y-m-d H:i:s');
            $info = Wantbuy::create($data);
            $userList = \app\admin\model\User::field('id,is_follow,nickname,wechat_openid')
                ->where(['is_follow'=>1,'status'=>'normal'])
                ->where('member_expire_time','>',$data['create_time'])
                ->select();
            if($userList){ //用户发布了求购只给是会员并已关注的用户发消息（现在微信没有群发功能，群发要注册第三方，所以只能先循环发送，）
                $datas=[
                    "first"=> "您好，苗木超市小程序有最新求购信息发布，请及时关注",
                    "keyword1"=> $name,
                    "keyword2"=> "*****",
                    "keyword3"=> $user['nickname'],
                    "keyword4"=> $data['create_time'],
                    "remark"=> "进入苗木超市小程序，查看更多详情",
                ];
                $template_num = Cache::get(TEMPLATE1);
                foreach ($userList as $v){
                    if($template_num < 60 && $v['id'] != $user['id']){
                        $template_num = $template_num+1;
                        sendMessage($v['wechat_openid'],$datas,TEMPLATE1);
                    }
                }
                Cache::set(TEMPLATE1,$template_num,90);
            }
        }
        if($info){
            $this->success("成功");
        }
    }


    /**
     * 求购详情
     */
    public function myBuySubDetails()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $info = Wantbuy::get(['user_id'=>$user['id'],'id'=>$id]);
        if($info){
            $info['imgs'] = ImageUtil::handleMore( $info['imgs'],false);
            $this->success("获取成功",$info);
        }
        $this->error("不存在");
    }

    /**
     * 我的求购删除
     */
    public function supplySubDel()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $info = Wantbuy::update(['is_del'=>1],['user_id'=>$user['id'],'id'=>$id]);
        if($info){
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }


    /**
     * 我的报价
     */
    public function myQuote()
    {
        $user = $this->auth->getUser();
        $wantbuy_id = $this->request->param('wantbuy_id');
        $imgs = $this->request->param('imgs');
        $price = $this->request->param('price');
        $company_name = $this->request->param('company_name');
        $phone = $this->request->param('phone');
        $introduction = $this->request->param('introduction');
        $address = $this->request->param('address');
        $num = $this->request->param('num');
        if(!$wantbuy_id || !$num || !$imgs || !$price || !$company_name || !$phone || !$introduction || !$address){
            $this->error("参数不全");
        }

        $data=[
            'user_id'=>$user['id'],
            'wantbuy_id'=>$wantbuy_id,
            'imgs'=>$imgs,
            'price'=>$price,
            'company_name'=>$company_name,
            'phone'=>$phone,
            'introduction'=>$introduction,
            'address'=>$address,
            'num'=>$num,
            'create_time'=>date('Y-m-d H:i:s'),
        ];
        $info = NurseryWantbuyOffer::create($data);
        if($info){
            $this->success("提交成功");
        }
        $this->error("提交失败");
    }


}
